﻿using FireChat.Server.Database.Table;

namespace FireChat.Share.Database.Util;


/// <summary>
/// 数据表管理类
/// </summary>
/// <typeparam name="T">数据表类型</typeparam>
public static class DataTableManager<T> where T : DataTableBase, new()
{
    /// <summary>
    /// 初始化数据库
    /// </summary>
    static DataTableManager()
    {
        DatabaseManager.Default.CreateTable<T>();
    }



    /// <summary>
    /// 插入数据到库
    /// </summary>
    public static int Insert(T data)
    {
        data.CreatedTime = DateTime.Now;
        return DatabaseManager.Default.Insert(data);
    }

    /// <summary>
    /// 删除一个数据
    /// </summary>
    /// <param name="primaryKey">数据主键</param>
    public static int Delete(object primaryKey)
    {
        return DatabaseManager.Default.Delete<T>(primaryKey);
    }

    /// <summary>
    /// 更新数据
    /// </summary>
    /// <param name="primaryKey">主键</param>
    /// <param name="updateMethod">更新方法</param>
    public static int Update(object primaryKey, Func<T, T> updateMethod)
    {
        var value = DatabaseManager.Default.Get<T>(primaryKey);
        var updated = updateMethod(value);

        updated.LastUpdateTime = DateTime.Now;

        return DatabaseManager.Default.Update(updated);
    }

    /// <summary>
    /// 查询数据
    /// </summary>
    /// <param name="express">筛选表达式</param>
    public static IEnumerable<T> Select(Func<T, bool>? express = null)
    {
        var all = DatabaseManager.Default.Table<T>();

        return express == null ? all : all.Where(express);
    }

    /// <summary>
    /// 查询一个符合条件的数据是否存在
    /// </summary>
    public static bool Exists(Func<T, bool> express)
    {
        return Select(express)?.FirstOrDefault() is T;
    }
}